import MessageHash from "./MessageHash";
import MessageBody from "./MessageBody";
import MessageBodyCallback from "./MessageBodyCallback";
import Message from "./Message";
import ServerAckCallback from "./ServerAckCallback";
import ResetCallback  from "./ResetCallback";

class SortedHash {
    private uuids: string[];
    private hash: MessageHash;
    private allMessages: MessageBody[];
    public newMsgCallback!: MessageBodyCallback;
    public onServerAckCallback!: ServerAckCallback;
    public onRemoveCallback!: ServerAckCallback;
    public resetCallback!:ResetCallback;
    constructor() {
        this.uuids = [];
        this.hash = {};
        this.allMessages = [];
        this.newMsgCallback = (msg: MessageBody) => { };
        this.onServerAckCallback = ()=>{};
        this.resetCallback = ()=>{};
    }
    public push(message: Message) {
        if (message.body != undefined) {
            if (this.uuids.indexOf(message.uuid) == -1) {
                this.uuids.push(message.uuid);
                this.hash[message.uuid] = message.body;
                this.allMessages.push(message.body);
                //开始调用回调
                this.newMsgCallback(message.body,message.uuid);
            }
        }
    }
    public size():number {
        return this.uuids.length;
    }
    public reset(){
        this.uuids = [];
        this.allMessages = [];    
        this.resetCallback();      
    }
    public all(): MessageBody[] {
        return this.allMessages;
    }
    public markAsServerAck(uuid:string){
        let indexOf = this.uuids.indexOf(uuid);
        if(indexOf!=-1){
            this.hash[uuid].sent = true
            this.allMessages[indexOf].sent = true
            this.onServerAckCallback(uuid,indexOf);
        }        
    }
    /**
     * 消息需要被删除...因为发送失败;
     */
    public markAsFailed(uuid:string){
       this.remove(uuid); 
    }

    public markAsRollback(uuid:string){
        this.remove(uuid);
    }
    public remove(uuid:string){
        let indexOf = this.uuids.indexOf(uuid);
        if (indexOf != -1) {
            delete (this.hash[uuid])
            this.allMessages.splice(indexOf, 1)
            this.uuids.splice(indexOf, 1)
            this.onRemoveCallback(uuid, indexOf);
        } 
    }
}
export default SortedHash